package org.reborn.utils

import java.io.{InputStream,FileInputStream}

/**
 * A convenience class for loading files from various locations.
 * 
 * Methods return InputStream objects. Users of these methods must take
 * care to close the InputStream when finished with it.
 */
object FileUtil {
  val CLASSPATH_PREFIX = "classpath:"
  val FILESYSTEM_PREFIX = "filesystem:"

  /**
   * Loads a file from the classpath and returns it as an InputStream.
   * @param fileName the fully-qualified name of a file on the classpath
   * @returns Some(InputStream) if the file was found, otherwise None
   */
  def LoadFromClasspath(fileName:String):Option[InputStream] = {
	val absFilename = if(fileName.startsWith("/")) fileName.substring(1) else fileName
	
	val fileStream = ClassLoader.getSystemClassLoader.getResourceAsStream(absFilename) 
	Option(fileStream)
  }
  
  /**
   * Loads a file from the file system and returns it as an InputStream.
   * @param fileName the relative or absolute name of a file on the file system
   * @returns Some(InputStream) if the file was found and opened successfully, otherwise None
   */
  def LoadFromFileSystem(fileName:String):Option[InputStream] = {
	try{
	  Option(new FileInputStream(fileName))
	}
	catch{
		case _ => None
	}
  }

  /**
   * Loads a file from various locations, depending on the fileName's prefix.
   * valid prefixes: 
   *   classpath: Loads from the classpath
   *   filesystem: Loads from the filesystem
   *   -none-: If left empty, it will by default load from the filesystem 
   * @param fileName the name of the file to load
   * @return Some(InputStream) if the file was found and opened successfully, otherwise None
   */
  def Load(fileName:String):Option[InputStream] = {
	if(fileName.startsWith(CLASSPATH_PREFIX)){
	  LoadFromClasspath(fileName.substring(CLASSPATH_PREFIX.length))
	}
	else if(fileName.startsWith(FILESYSTEM_PREFIX)){
	  LoadFromFileSystem(fileName.substring(FILESYSTEM_PREFIX.length))
	}
	else{
	  LoadFromFileSystem(fileName)
	}
  }
}